package com.encyclopedia.service;


import com.aliyun.oss.OSSClient;
import com.encyclopedia.result.JsonRequest;
import com.encyclopedia.result.exenum.RequestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.UUID;

/**
 * 警告     该类只能用来上传或下载文件图片
 * 重复一次  该类只能用来上传图片
 */

@Service
public class OssService {
    @Autowired
    private OSSClient OSSClient;
    @Value("${aliyun.oss.bucketName}")
    private String ALIYUN_OSS_BUCKET_Name;

    @Value("${aliyun.oss.prefix}")
    private String ALIYUN_OSS_PREFIX;
    @Value("${aliyun.oss.endpoint}")
    private String ALIYUN_OSS_ENDPOINT;

    /**
     * @param multipartFile 文件
     * @param moduleName    当前模块名字 好管理文件
     * @return
     */
    public String OssAdd(MultipartFile multipartFile, String moduleName) {
        String url = null;
        try {

            //            //获取上传的文件的名字
            InputStream inputStream = multipartFile.getInputStream();
            String filename = multipartFile.getOriginalFilename();
            //            //随机uuid是为了拼接文件名，防止用户上传两个名字相同的文件后覆盖掉前一个
            UUID uuid = UUID.randomUUID();
            filename = ALIYUN_OSS_PREFIX + moduleName + "/" + uuid + filename;
            OSSClient.putObject(ALIYUN_OSS_BUCKET_Name, filename, inputStream);
            url = "https://" + ALIYUN_OSS_BUCKET_Name + "." + ALIYUN_OSS_ENDPOINT + "/" + filename;
        } catch (Exception e) {
            //TODO  需要修改
            JsonRequest<Objects> jsonRequest = JsonRequest.error(RequestException.DELETE_ERROR);
        }
        return url;
    }

    /**
     * 删除oss文件
     *
     * @param url
     * @return
     */
    public Boolean OssRemove(String url) {
        boolean fileBoolean = false;
        try {
            URL url1 = new URL(url);
            url = url1.getPath();
            OSSClient.deleteObject(ALIYUN_OSS_BUCKET_Name, url);
            fileBoolean = true;
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        return fileBoolean;
    }


}
